<template>
  <div>
    <!-- 首页 -->
    <div class="header-box">
      <div class="header-left">
        <el-button
          type="primary"
          link
          @click="handleCut(1)"
          v-if="cut_status == 2"
        >
          <span class="mr-[0.2rem]">检查模式</span>
          <el-icon><Switch /></el-icon>
        </el-button>
        <el-button type="primary" link @click="handleCut(2)" v-else>
          <span class="mr-[0.2rem]">管理模式</span>
          <el-icon><Switch /></el-icon>
        </el-button>
        <current-time class="time" />
      </div>

      <theme-title />

      <div class="header-right">
        <camera-status class="h-[60%] mr-[3rem]" />
        <network-status />
      </div>
    </div>

    <!--二级出口 -->
    <!-- <router-view /> -->

    <router-view v-slot="{ Component }">
      <transition name="fade" mode="out-in">
        <component :is="Component" />
      </transition>
    </router-view>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import {
  ElMessage,
  ElMessageBox,
  ElLoading,
  ElNotification,
} from "element-plus";
import { useUserStore } from "@/pinia";
import { storeToRefs } from "pinia";
import { useRouter } from "vue-router";

import CurrentTime from "./component/CurrentTime.vue";
import ThemeTitle from "./component/ThemeTitle.vue";
import NetworkStatus from "./component/NetworkStatus.vue";
import CameraStatus from "./component/CameraStatus.vue";

import CheckMode from "@/view/CheckMode/index.vue";

const useStore = useUserStore();
const { isDetection } = storeToRefs(useUserStore());

onMounted(() => {
  // if (isDetection.value == 1) fn();
});

const router = useRouter();

// 模式切换
const cut_status = ref(1); // 1:检测模式 2:检测模式
const handleCut = (type) => {
  cut_status.value = type;
  if (cut_status.value == 1) {
    router.push({ name: "customer_info" });
  } else {
    router.push({ name: "home_page" });
  }
};

const detectionList = ref([
  {
    id: 1,
    title: "网络",
    status: getRandomInt(1, 2),
  },
  {
    id: 2,
    title: "摄像头",
    status: getRandomInt(1, 2),
  },
  {
    id: 3,
    title: "初始化",
    status: 1,
  },
]);

const currentIndex = ref(-1);
const itemStates = ref({});
const isPaused = ref(false);
const error_title = ref("");
const fn = async () => {
  let index = 0;

  while (index < detectionList.value.length) {
    if (isPaused.value) {
      const continueProcess = await new Promise((resolve) => {
        ElMessageBox.confirm(
          `${error_title.value}已离线，检测已暂停，是否继续？`,
          "提示",
          {
            confirmButtonText: "继续",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => resolve(true))
          .catch(() => resolve(false));
      });

      if (!continueProcess) break;
      isPaused.value = false;
    }

    const item = detectionList.value[index];
    currentIndex.value = index;
    itemStates.value[item.id] = "loading";

    try {
      await new Promise((resolve) => {
        const loading = ElLoading.service({
          lock: true,
          text: `${item.title}检查中...`,
          background: "rgba(0, 0, 0, 0.7)",
        });
        setTimeout(() => {
          loading.close();
          if (item.status === 2) {
            isPaused.value = true;
            error_title.value = item.title;
          }
          resolve();
        }, 2000);
      });

      itemStates.value[item.id] = "success";
    } catch (error) {
      itemStates.value[item.id] = "error";
    } finally {
      await new Promise((resolve) => setTimeout(resolve, 500));
    }

    if (useStore.isDetection === 2) {
      isPaused.value = true;
      return;
    }

    index++;
  }

  // ElNotification.success("检测完成");
  ElNotification.success({
    title: "检测完成",
    // message: "所有检测项均通过",
    position: "bottom-left",
  });

  currentIndex.value = -1;
  useStore.updateIsDetection(2);
};

/**
 * 生成指定范围内的随机整数
 * @param {number} min - 最小值（包含）
 * @param {number} max - 最大值（包含）
 * @returns {number} 随机整数
 */
function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>

<style scoped lang="scss">
.header-box {
  @apply w-full h-[var(--header-height)] flex justify-between items-center overflow-hidden border-b-1 px-2;

  .header-left {
    @apply w-[20%] min-w-[13rem] h-full flex justify-between items-center px-1 box-border;

    .time {
      @apply h-full  flex justify-center items-center;
    }
  }

  .header-right {
    // background-color: red;
    @apply w-[20%] min-w-[13rem] h-full flex justify-end items-center;
  }
}

.home_header {
  @apply w-full flex justify-between items-center;
}

.home_card :deep(.el-card__header) {
  @apply px-[1rem] py-[0.3rem] !important;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>